﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;

using Betop.Lib.Core.Base;
using Betop.Lib.Common;
using Betop.Lib.Enums;
using Betop.Lib.Data;
using Betop.Lib.Utilities;

namespace Betop.Lib.Core.Attach
{
    public class AttachBO : CommonOperate<AttachInfo>
    {
        private const int BUFFER_SIZE = 10240;
        private AttachDAL _attach;
        private string _tableName;
        private int _index;//为了确保文件名唯一

        /// <summary>
        /// 附件保存的物理路径
        /// </summary>
        private string SavePath
        {
            get
            {
                return AppSetting.AttachPath + _tableName + "\\";
            }
        }

        protected override BaseDAL DAL
        {
            get
            {
                return _attach;
            }
        }

        public AttachBO(string tableName)
            : base(tableName)
        {
            this._tableName = tableName.ToString();
            _attach = new AttachDAL(tableName);
            _index = 0;
        }

        public AttachBO(TableName tableName):this(tableName.ToString())            
        {           
        }

        public AttachBO(TableName tableName, DBHelper db):this(tableName)
        {
            _attach.dbOper = base.dbOper = db;
        }

        public IEnumerable<AttachInfo> GetList(int bindID)
        {
            List<AttachInfo> list = _attach.GetList(bindID);
            DealList(list);
            return list;
        }

        public IEnumerable<AttachInfo> GetList(List<int> lstBindIDs)
        {
            List<AttachInfo> list = _attach.GetList(lstBindIDs);
            DealList(list);
            return list;
        }

        public override void Delete(object id)
        {
            AttachInfo info = this.GetInfo(id);

            if (File.Exists(SavePath + info.Path))
            {
                File.Delete(SavePath + info.Path);
            }

            base.Delete(id);          
        }

        public override void Delete(IEnumerable<int> ids)
        {
            foreach (int id in ids)
            {
                Delete(id);
            }
        }

        public override void Delete(IEnumerable<string> ids)
        {
            foreach (string id in ids)
            {
                Delete(id);
            }
        }

        public void DeleteByBindID(object bindID)
        {
            IEnumerable<int> ids = _attach.GetIDs(bindID);
            Delete(ids);
        }

        private void DealList(List<AttachInfo> list)
        {          
            string strUrl = GlobalVar.WebAppPath + "Common/FileDownLoad.aspx?TableName=" + _tableName + "&ID=";
            for (int i = 0; i < list.Count; i++)
            {
                list[i].Index = i + 1;
                list[i].DownloadUrl = strUrl + StrUtil.EncryptUrl(list[i].ID);
            }
        }

        public void Save(System.Web.HttpFileCollection files, int bindID)
        {
            for (int i = 0; i < files.Count; i++)
            {
                if (System.IO.Path.GetFileName(files[i].FileName) == "")
                {
                    continue;
                }
                Save(files[i], bindID);
            }
        }

        public void Save(System.Web.HttpPostedFile file, int bindID)
        {
            //using (TransactionScope scope = new TransactionScope())
            //{
            //try
            //{
            //    base.dbOper.BeginTrans();

                if (file.FileName == "")
                {
                    return;
                }
                AttachInfo info = new AttachInfo();
                info.Name = System.IO.Path.GetFileName(file.FileName);
                info.BindID = bindID;
                info.Type = file.ContentType;
                info.Size = file.ContentLength;
                if (!string.IsNullOrEmpty(AppSession.UserName))//用于外网直接调用
                {
                    info.CreatorID = AppSession.UserID;
                    info.CreatorName = AppSession.UserName;
                }
                info.InputTime = DateTime.Now;

                if (!System.IO.Directory.Exists(SavePath))
                {
                    System.IO.Directory.CreateDirectory(SavePath);
                }

                string newFileName = GenerateFileName() + System.IO.Path.GetExtension(info.Name);

                info.Path = newFileName;//数据库保存文件名，路径可以通过配置文件来实现将更灵活
                base.Save(info);

                file.SaveAs(SavePath + newFileName);

               // base.dbOper.CommitTrans();
            //    //scope.Complete();
            //}
            //catch (Exception ex)
            //{
            //    base.dbOper.RollbackTrans();
            //    //scope.Dispose();
            //    throw ex;
            //}
           

           // }

        }

        public void Download(int id)
        {
            AttachInfo info = base.GetInfo(id);
            System.Web.HttpContext context = System.Web.HttpContext.Current;

            string filePath = SavePath + info.Path;

            if (File.Exists(filePath))
            {
                string fileName = context.Server.UrlEncode(info.Name);
                context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
                context.Response.ContentType = info.Type;
                context.Response.CacheControl = "public";

                byte[] buffer = new byte[BUFFER_SIZE];
                FileStream fs = null;

                fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);

                try
                {
                    
                    long length = fs.Length;
                    while (length > 0L)
                    {
                        if (context.Response.IsClientConnected)
                        {
                            int count = fs.Read(buffer, 0, BUFFER_SIZE);
                            context.Response.OutputStream.Write(buffer, 0, count);
                            length -= count;
                        }
                    }
                    context.Response.Flush();
                }
                catch (Exception ex)
                {
                    context.Response.Write("Error : " + ex.Message);
                }
                finally
                {
                    if (fs != null)
                    {
                        fs.Close();
                    }
                    context.Response.End();
                }
            }
            else
            {
                context.Response.Write("<script type='text/javascript'>alert('该文件不存在');history.back();</script>");
                context.Response.End();
            }

        }

        public void CopyAttach(List<int> lstAttachIDs, int bindID)
        {
            //_attach.CopyAttach(lstAttachIDs, bindID);

            List<AttachInfo> list = _attach.GetListByIDs(lstAttachIDs);

            foreach (AttachInfo info in list)
            {
                info.ID = 0;
                info.BindID = bindID;

                string oldPath = info.Path;

               
                string newFileName = GenerateFileName() + System.IO.Path.GetExtension(info.Name);
                info.Path = newFileName;//数据库保存文件名，路径可以通过配置文件来实现将更灵活

                base.Save(info);

                File.Copy(SavePath + oldPath, SavePath + info.Path);

               // file.SaveAs(SavePath + newFileName);
            }
        }

        /// <summary>
        /// 产生一个不带扩展名的文件名
        /// </summary>
        /// <returns></returns>
        private string GenerateFileName()
        {
            _index++;
            int userID = 0;
            if (AppSession.UserName != null)
            {
                userID = AppSession.UserID;
            }
            string fileName = userID + "_" + DateTime.Now.Ticks + "_" + _index;
            return fileName;
        }

        /// <summary>
        /// 保存后返回路径的，目前用于外部邮件
        /// </summary>
        /// <param name="file">附件的二进制数组</param>
        /// <param name="oldName">原文件名，主要是用于获得扩展名</param>
        /// <returns>生成的新的文件名</returns>
        public string Save(byte[] file,string oldName)
        {
            string newFileName = GenerateFileName() + System.IO.Path.GetExtension(oldName);
            if (!Directory.Exists(SavePath))
            {
                Directory.CreateDirectory(SavePath);
            }
            string path = SavePath + newFileName;

            FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write);
            fs.Write(file, 0, file.Length);

            fs.Flush();

            fs.Close();

            return newFileName;
        }
       
    }
}
